package com.pj.compose.ui.compose

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*
import com.pj.compose.common.config.StringExt.debugPrint
import kotlinx.coroutines.flow.distinctUntilChanged


@Composable
fun LoadMoreListHandler(
    listState: LazyListState,
    buffer: Int = 1,
    pageSize: Int = 10,
    onLoadMore: () -> Unit
) {
    val loadMore = remember {
        derivedStateOf {
            val layoutInfo = listState.layoutInfo
            val totalItemsCount = layoutInfo.totalItemsCount
            var b = false
            if (totalItemsCount > pageSize){
                val firstVisibleIndex = layoutInfo.visibleItemsInfo.firstOrNull()?.index ?: 0
                val lastVisibleItemIndex = (layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0) + 1
                b = totalItemsCount in pageSize until lastVisibleItemIndex + buffer
            }
//            "firstVisibleIndex:${firstVisibleIndex},lastVisibleItemIndex:${lastVisibleItemIndex},totalItemsCount:${totalItemsCount},buffer:${buffer},result:${b}".debugPrint()
            b
        }
    }
    LaunchedEffect(loadMore)
    {
        snapshotFlow { loadMore.value }
            .distinctUntilChanged()
            .collect {
                if (it) {
                    onLoadMore()
                }
            }
    }

}

